
#include "stdafx.h"
#include "ProcessList.h"
#ifndef _BIDCONTROL_
#include "Utility.h"
#else
#include "..\\..\\BidServer\\Utility.h"
#endif

CProcessList::CProcessList()
{
	m_hProcThread = m_hProcEvent = nullptr; m_ProcThreadRunning = false;
}

CProcessList::~CProcessList()
{
}

DWORD WINAPI StartThread_ProcessList(LPVOID p)
{
	CProcessList *pList = (CProcessList*)p; if (!pList) return -1;
	pList->ProcessThread();
	pList->m_ProcThreadRunning = false;
	return 0;
}
void CProcessList::Start()
{
	if (IsRunning()) return;
	if (!m_hProcEvent) m_hProcEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
	if (!m_hProcThread)
	{
		m_ProcThreadRunning = true; m_hProcThread = CreateThread(NULL, 0, StartThread_ProcessList, this, 0, NULL);
	}
}

void CProcessList::Stop()
{
	if (m_hProcThread)
	{
		m_ProcStopThread = true; if (m_hProcEvent) SetEvent(m_hProcEvent);
		while (IsRunning()) Sleep(10);
	}
	if (m_hProcEvent)
	{
		CloseHandle(m_hProcEvent); m_hProcEvent = nullptr;
	}
	clear();
}

bool CProcessList::IsRunning()
{
	return CheckThread(m_hProcThread, m_ProcThreadRunning);
}

void CProcessList::ProcessThread()
{
	if (!m_hProcEvent) return;
	for (m_ProcStopThread = false; !m_ProcStopThread;)
	{
		CLinkedNode *pNode = GetNode();
		if (!pNode)
			WaitForSingleObject(m_hProcEvent, INFINITE);
		else
		{
			ProcessNode(pNode);
			if (pNode) delete pNode;
		}
	}
}

bool CProcessList::AddFirstNode(CLinkedNode *pAdd)
{
	if (!CLinkedList::AddNodeAtFirst(pAdd)) return false;
	if (m_hProcEvent) SetEvent(m_hProcEvent);
	return true;
}

bool CProcessList::AddNode(CLinkedNode *pAdd)
{
	if (!CLinkedList::AddNode(pAdd)) return false;
	if (m_hProcEvent) SetEvent(m_hProcEvent);
	return true;
}

